package com.caiying.dota.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class EncriptUtil {
	public static String MD5(byte[] source){  
		String s = null;
		char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', 
				'9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); 
			char str[] = new char[16 * 2];
			int k = 0; 
			for (int i = 0; i < 16; i++) { 
				byte byte0 = tmp[i]; 
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 
				str[k++] = hexDigits[byte0 & 0xf]; 
			}
			s = new String(str); 
		} catch (Exception e) {
			
		}
		return s;
	} 
	
	public static String encrypt(String src){
		return encrypt(src, "UTF-8", "MD5");
	}
	
	public static String encrypt(String src, String encoding, String method){
		MessageDigest md = null;
		if ("MD5".equals(method)) {
			try {
				md = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException e) {
			}
		} else if ("SHA-1".equals(method)) {
			try {
				md = MessageDigest.getInstance("SHA-1");
			} catch (NoSuchAlgorithmException e) {
			}
		} else {
			throw new IllegalArgumentException("Only MD5 or SHA-1 supported.");
		}
		try {
			md.update(src.getBytes(encoding == null?encoding:"UTF-8"));
			byte[] bytes = md.digest();
			return bytesToString(bytes);
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException("UnsupportedEncoding:" + encoding);
		}
	}
	
	public static String bytesToString(byte[] bytes) {
		StringBuilder hs = new StringBuilder();
		for (int n = 0; n < bytes.length; n++) {
			String stmp = java.lang.Integer.toHexString(bytes[n] & 0xFF);
			if (stmp.length() == 1){
				hs.append("0").append(stmp);
			}else{
				hs.append(stmp);
			}
		}
		return hs.toString().toLowerCase();
	}
}
